const LabelService = require('../service/Label.service')

const verifyLabelExists = async (ctx, next) => {
  const { labels } = ctx.request.body
  const newLabels = []
  for (const name of labels) {
    // 查询传入的label是否已经存在
    const labelResult = await LabelService.getLabelByName(name)
    const label = { name }
    if (!labelResult) {
      // 不存在则创建label
      const result = await LabelService.addLabel(name)
      Object.assign(label, { id: result.insertId })
    } else {
      Object.assign(label, { id: labelResult.id })
    }
    newLabels.push(label)
  }
  ctx.labels = newLabels
  await next()
}

module.exports = {
  verifyLabelExists
}
